package com.mydomain.debtbook;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ActivityGroup;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

public class ListGroupActivityGroup extends ActivityGroup {

	public static ListGroupActivityGroup group;

	private ArrayList<View> history;
	private boolean isEdit;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		this.history = new ArrayList<View>();
		group = this;
		super.onCreate(savedInstanceState);
		isEdit = false;
		// Start the root activity withing the group and get its view
		View view = getLocalActivityManager().startActivity(
				"Group",
				new Intent(this, ListGroupActivity.class)
						.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
				.getDecorView();

		// Replace the view of this ActivityGroup
		replaceView(view);
	}

	public void replaceView(View v) {

		// Adds the old one to history
		history.add(v);
		// Changes this Groups View to the new View.
		setContentView(v);

	}

	public void back() {
		if (history.size() > 0) {
			history.remove(history.size() - 1);
			if (history.size() > 0) {
				setContentView(history.get(history.size() - 1));
			} else {
				finish();
			}
		} else {
			finish();
		}
	}

	@Override
	public void onBackPressed() {
		ListGroupActivityGroup.group.back();
		return;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_viewgroup, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.mvg_new:
			startActivity(new Intent(this, ListNewGroupActivity.class));
			return true;
		case R.id.mvg_edit:
			if (isEdit) {

				Intent intent = new Intent(this, ListGroupActivity.class);
				replaceContentView("editGroup", intent);
				isEdit = false;
			} else {

				Intent intent = new Intent(this, EditGroupActivity.class);
				replaceContentView("editGroup", intent);

				isEdit = true;
			}

		}
		return false;
	}

	public void replaceContentView(String id, Intent newIntent) {
		View view = ((ActivityGroup) (this))
				.getLocalActivityManager()
				.startActivity(id,
						newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
				.getDecorView();

		((Activity) this).setContentView(view);

	}

}
